using Publicuse.Entity;
using Publicuse.Interface;
using Publicuse.Interface;
using Publicuse.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Publicuse.Export
{
    /// <summary>
    /// / 用户角色权限辅助类
    /// </summary>
    public class URPermissionExport
    {

        /// <summary>
        /// 获取登陆用户角色权限信息列表
        /// </summary>
        /// <param name="uCode"></param>
        /// <param name="urPermissionService"></param>
        /// <returns></returns>
        public static List<UserModule> GetUserLoginRoleResourceListReset(string uCode, IMySqlSugarService urPermissionService)
        {
            var roleTable = TableAtributeUtil.GetTable<Role>();
            var authorityTable = TableAtributeUtil.GetTable<Menu>();
            var urPermissionTable = TableAtributeUtil.GetTable<URPermission>();
            List<Menu> urPermissions = new List<Menu>();
            List<UserModule> modules = new List<UserModule>();
            string value = string.Empty;
            //LoginCacheUtil.GetLoginCacheUtil.GetUserRole(uCode, out value);
            string rids = value.Split('-')[1];
            var ridlist = rids.Split(',');
            int uId = Convert.ToInt32(value.Split('-')[0]);
            CommonResult result = new CommonResult();
            string msg = string.Empty;
            foreach (var rid in ridlist)
            {
                var aIds = string.Empty;
                if (string.Compare(uCode, "admin", true) != 0 && string.Compare(uCode, "sysadmin", true) != 0)
                {
                    string sqlb = string.Format("select aIds  from {0} ", urPermissionTable);
                    var tupa = new Tuple<string, string, ExcuteType>("Id", rid.ToString(), ExcuteType.Equal);
                    var tupb = new Tuple<string, string, ExcuteType>("uid", uId.ToString(), ExcuteType.Equal);
                    var pars = new List<Tuple<string, string, ExcuteType>>() { tupa, tupb };
                    var datab = urPermissionService.GetDataTable(sqlb, pars, out msg);
                    if (datab.Rows.Count == 0)
                    {
                        continue;
                    }
                    else
                    {
                        if (uCode == "admin" || uCode == "sysadmin")
                        {
                            aIds = datab.Rows[0]["aIds"].ToString().Trim(',');
                        }
                        else
                        {
                            aIds = datab.Rows[0]["aIds"].ToString().Trim(',');
                        }
                    }
                }

                string sql = string.Empty;
                if (string.Compare(uCode, "admin", true) == 0 || string.Compare(uCode, "sysadmin", true) == 0)
                {
                    sql = string.Format("select * from {0} order by Id desc ", authorityTable);
                }
                else
                {
                    sql = string.Format("select * from {0} a where aid in({1}) order by Id desc ", authorityTable, aIds);
                }
                urPermissions=urPermissionService.Query<Menu>(sql,  out msg);
                if (string.IsNullOrEmpty(msg))
                {
                    if (urPermissions.Count > 0)
                    {
                        //获取用户角色模块信息
                        var moduleList = urPermissions.Where(o => o.aType == 1).ToList();
                        foreach (var item in moduleList)
                        {
                            UserModule module = new UserModule();
                            module.name = item.aName;
                            module.amoduleIndex = item.amoduleIndex;
                            module.ahtmlIcon = item.ahtmlIcon;
                            module.aCode = item.aCode;
                            //获取用户角色模块菜单信息
                            var menuList = urPermissions.Where(o => o.aType == 2 && o.aParentId == item.Id && o.abName == "").ToList();
                            foreach (var menu in menuList)
                            {
                                UserMenu userMenu = new UserMenu();

                                userMenu.name = menu.aName;
                                userMenu.url = menu.ahtmlUrl;
                                userMenu.ahtmlIcon = menu.ahtmlIcon;
                                userMenu.amoduleIndex = menu.amoduleIndex;
                                userMenu.ismenu = menu.ahtmlUrl == "" ? false : true;
                                userMenu.aCode = menu.aCode;
                                userMenu.aId = menu.Id;

                                var ishave = false;
                                //如果已经存在该模块菜单信息则不添加
                                foreach (var md in modules)
                                {
                                    if (!string.IsNullOrEmpty(menu.aName))
                                    {
                                        ishave = md.userMenu.Any(o => o.aCode == menu.aCode);
                                        if (ishave)
                                        {
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        ishave = md.userMenu.Any(o => o.aCode == menu.aCode);
                                        if (ishave)
                                        {
                                            break;
                                        }
                                    }
                                }
                                if (!ishave)
                                {
                                    if (modules.Count > 0)
                                    {
                                        var old = modules.Any(o => o.aCode == module.aCode);
                                        if (old)
                                        {
                                            modules.Where(o => o.aCode == module.aCode).FirstOrDefault().userMenu.Add(userMenu);
                                            modules.Where(o => o.aCode == module.aCode).FirstOrDefault().userMenu = modules.Where(o => o.aCode == module.aCode).FirstOrDefault().userMenu.OrderBy(o => o.amoduleIndex).ToList();
                                        }
                                        else
                                        {
                                            module.userMenu.Add(userMenu);
                                            module.userMenu = module.userMenu.OrderBy(o => o.amoduleIndex).ToList();
                                        }
                                        var menuListb = urPermissions.Where(o => o.aType == 2 && o.aParentId == menu.Id && o.abName == "").ToList();
                                        foreach (var itemb in menuListb)
                                        {
                                            UserMenub menub = new UserMenub()
                                            {
                                                aCode = itemb.aCode,
                                                ahtmlIcon = itemb.ahtmlIcon,
                                                amoduleIndex = itemb.amoduleIndex,
                                                name = itemb.aName,
                                                url = itemb.ahtmlUrl,
                                                aId = itemb.Id
                                            };
                                            module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus.Add(menub);
                                            module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus = module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus.OrderBy(o => o.amoduleIndex).ToList();
                                            var nowmenu = module.userMenu.FirstOrDefault(o => o.aCode == userMenu.aCode).childMenus.FirstOrDefault(o => o.aId == itemb.Id);
                                            AddMenuData(urPermissions, itemb.Id, ref nowmenu);
                                        }
                                    }
                                    else
                                    {
                                        module.userMenu.Add(userMenu);
                                        module.userMenu = module.userMenu.OrderBy(o => o.amoduleIndex).ToList();
                                        var menuListb = urPermissions.Where(o => o.aType == 2 && o.aParentId == menu.Id && o.abName == "").ToList();
                                        foreach (var itemb in menuListb)
                                        {
                                            UserMenub menub = new UserMenub()
                                            {
                                                aCode = itemb.aCode,
                                                ahtmlIcon = itemb.ahtmlIcon,
                                                amoduleIndex = itemb.amoduleIndex,
                                                name = itemb.aName,
                                                url = itemb.ahtmlUrl,
                                                aId = itemb.Id
                                            };
                                            module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus.Add(menub);
                                            module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus = module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus.OrderBy(o => o.amoduleIndex).ToList();
                                            var nowmenu = module.userMenu.FirstOrDefault(o => o.aCode == userMenu.aCode).childMenus.FirstOrDefault(o => o.aId == itemb.Id);
                                            AddMenuData(urPermissions, itemb.Id, ref nowmenu);
                                        }
                                    }
                                }
                            }

                            InitAuthro(urPermissions, item, modules, module);
                        }
                    }
                }
            }
            if (modules.Count > 0)
            {
                modules = modules.OrderBy(o => o.amoduleIndex).ToList();
                List<UserAction> uActions = new List<UserAction>();
                foreach (var item in modules)
                {
                    foreach (var action in item.userAction)
                    {
                        uActions.Add(action);
                    }
                }
                //LoginCacheUtil.GetLoginCacheUtil.SaveLoginAction(uCode, uActions);
                //LoginCacheUtil.GetLoginCacheUtil.SaveLoginActionList(uCode, uActions);
                //DoTaskDlg doTask = DoTask;
                //doTask.BeginInvoke(rids,urPermissionService,null,null);
            }
            return modules;
        }

        /// <summary>
        /// 获取登陆用户角色权限信息列表
        /// </summary>
        /// <param name="rids"></param>
        /// <param name="uId"></param>
        /// <param name="uCode"></param>
        /// <param name="urPermissionService"></param>
        /// <returns></returns>
        public static List<UserModule> GetUserLoginRoleResourceList(string rids, int uId,string uCode,IMySqlSugarService urPermissionService)
        {
            var roleTable = TableAtributeUtil.GetTable<Role>();
            var authorityTable = TableAtributeUtil.GetTable<Menu>();
            var urPermissionTable = TableAtributeUtil.GetTable<URPermission>();
            List<Menu> urPermissions = new List<Menu>();
            List<UserModule> modules = new List<UserModule>();
            var ridlist = rids.Split(',');
            CommonResult result = new CommonResult();
            string msg = string.Empty;
            foreach (var rid in ridlist)
            { 
                var aIds = string.Empty;
                if (string.Compare(uCode, "admin",true)!=0 && string.Compare(uCode,"sysadmin",true)!=0)
                {
                    string sqlb = string.Format("select aIds  from {0} ", urPermissionTable);
                    var tupa = new Tuple<string, string, ExcuteType>("rId", rid.ToString(), ExcuteType.Equal);
                    var tupb = new Tuple<string, string, ExcuteType>("uId", uId.ToString(), ExcuteType.Equal);
                    var pars = new List<Tuple<string, string, ExcuteType>>() { tupa, tupb };
                    var datab = urPermissionService.GetDataTable(sqlb, pars, out msg);
                    if (datab.Rows.Count == 0)
                    {
                        continue;
                    }
                    else
                    {
                        if (uCode == "admin" || uCode=="sysadmin")
                        {
                            aIds = datab.Rows[0]["aIds"].ToString().Trim(',');
                        }
                        else
                        {
                            aIds = datab.Rows[0]["aIds"].ToString().Trim(',');
                        }
                    }
                }
                
                string sql = string.Empty;
                if (string.Compare(uCode, "admin",true) == 0 || string.Compare(uCode, "sysadmin", true) == 0)
                {
                    sql = string.Format("select * from {0} where aStatus=1 order by Id desc ", authorityTable);
                }
                else
                {
                    sql = string.Format("select * from {0} a where aStatus=1 and Id in({1}) order by Id desc ", authorityTable, aIds);
                }
                urPermissions=urPermissionService.Query<Menu>(sql, out msg);
                if (string.IsNullOrEmpty(msg))
                {
                    if (urPermissions.Count > 0)
                    {
                        //获取用户角色模块信息
                        var moduleList = urPermissions.Where(o => o.aType == 1).ToList();
                        foreach (var item in moduleList)
                        {
                            UserModule module = new UserModule();
                            module.name = item.aName;
                            module.amoduleIndex = item.amoduleIndex;
                            module.ahtmlIcon = item.ahtmlIcon;
                            module.aCode = item.aCode;
                            //获取用户角色模块菜单信息
                            var menuList = urPermissions.Where(o => o.aType == 2 && o.aParentId == item.Id && o.abName == "").ToList();
                            foreach (var menu in menuList)
                            {
                                UserMenu userMenu = new UserMenu();

                                userMenu.name = menu.aName;
                                userMenu.url = menu.ahtmlUrl;
                                userMenu.ahtmlIcon = menu.ahtmlIcon;
                                userMenu.amoduleIndex = menu.amoduleIndex;
                                userMenu.ismenu = menu.ahtmlUrl == "" ? false : true;
                                userMenu.aCode = menu.aCode;
                                userMenu.aId = menu.Id;

                                var ishave = false;
                                //如果已经存在该模块菜单信息则不添加
                                foreach (var md in modules)
                                {
                                    if (!string.IsNullOrEmpty(menu.aName))
                                    {
                                        ishave = md.userMenu.Any(o => o.aCode == menu.aCode);
                                        if (ishave)
                                        {
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        ishave = md.userMenu.Any(o => o.aCode == menu.aCode);
                                        if (ishave)
                                        {
                                            break;
                                        }
                                    }
                                }
                                if (!ishave)
                                {
                                    if (modules.Count > 0)
                                    {
                                        var old = modules.Any(o => o.aCode == module.aCode);
                                        if (old)
                                        {
                                            modules.Where(o => o.aCode == module.aCode).FirstOrDefault().userMenu.Add(userMenu);
                                            modules.Where(o => o.aCode == module.aCode).FirstOrDefault().userMenu = modules.Where(o => o.aCode == module.aCode).FirstOrDefault().userMenu.OrderBy(o => o.amoduleIndex).ToList();
                                        }
                                        else
                                        {
                                            module.userMenu.Add(userMenu);
                                            module.userMenu = module.userMenu.OrderBy(o => o.amoduleIndex).ToList();
                                        }
                                        var menuListb = urPermissions.Where(o => o.aType == 2 && o.aParentId == menu.Id && o.abName == "").ToList();
                                        foreach (var itemb in menuListb)
                                        {
                                            UserMenub menub = new UserMenub()
                                            {
                                                aCode = itemb.aCode,
                                                ahtmlIcon = itemb.ahtmlIcon,
                                                amoduleIndex = itemb.amoduleIndex,
                                                name = itemb.aName,
                                                url = itemb.ahtmlUrl,
                                                aId = itemb.Id
                                            };
                                            module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus.Add(menub);
                                            module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus = module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus.OrderBy(o => o.amoduleIndex).ToList();
                                            var nowmenu = module.userMenu.FirstOrDefault(o => o.aCode == userMenu.aCode).childMenus.FirstOrDefault(o => o.aId == itemb.Id);
                                            AddMenuData(urPermissions, itemb.Id, ref nowmenu);
                                        }
                                    }
                                    else
                                    {
                                        module.userMenu.Add(userMenu);
                                        module.userMenu = module.userMenu.OrderBy(o => o.amoduleIndex).ToList();
                                        var menuListb = urPermissions.Where(o => o.aType == 2 && o.aParentId == menu.Id && o.abName == "").ToList();
                                        foreach (var itemb in menuListb)
                                        {
                                            UserMenub menub = new UserMenub()
                                            {
                                                aCode=itemb.aCode,
                                                ahtmlIcon=itemb.ahtmlIcon,
                                                amoduleIndex=itemb.amoduleIndex,
                                                name=itemb.aName,
                                                url=itemb.ahtmlUrl,
                                                aId=itemb.Id
                                            };
                                            module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus.Add(menub);
                                            module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus = module.userMenu.FirstOrDefault(o => o.aId == userMenu.aId).childMenus.OrderBy(o => o.amoduleIndex).ToList();
                                            var nowmenu = module.userMenu.FirstOrDefault(o => o.aCode == userMenu.aCode).childMenus.FirstOrDefault(o => o.aId == itemb.Id);
                                            AddMenuData(urPermissions, itemb.Id,ref nowmenu);
                                        }
                                    }
                                }
                            }

                            InitAuthro(urPermissions, item, modules, module);
                        }
                    }
                }
            }
            if (modules.Count > 0)
            {
                modules = modules.OrderBy(o => o.amoduleIndex).ToList();
                List<UserAction> uActions = new List<UserAction>();
                foreach (var item in modules)
                {
                    foreach (var action in item.userAction)
                    {
                        uActions.Add(action);
                    }
                }
                //LoginCacheUtil.GetLoginCacheUtil.SaveLoginAction(uCode, uActions);
                //LoginCacheUtil.GetLoginCacheUtil.SaveLoginActionList(uCode, uActions);

                //DoTaskDlg doTask = DoTask;
                //doTask.BeginInvoke(rids,urPermissionService,null,null);
            }
            return modules;
        }

        /// <summary>
        /// 递归添加模块菜单信息
        /// </summary>
        /// <param name="urPermissions"></param>
        /// <param name="aId"></param>
        private static void AddMenuData(List<Menu> urPermissions, long aId, ref UserMenub module)
        {
            var menuList = urPermissions.Where(o => o.aType == 2 && o.aParentId == aId && o.abName == "").ToList();
            foreach (var item in menuList)
            {
                UserMenu menu = new UserMenu()
                {
                    aCode = item.aCode,
                    ahtmlIcon = item.ahtmlIcon,
                    amoduleIndex = item.amoduleIndex,
                    name = item.aName,
                    url = item.ahtmlUrl,
                    aId=item.Id
                };
                var aCode = module.aCode;
                module.userMenu.Add(menu);
                module.userMenu = module.userMenu.OrderBy(o => o.amoduleIndex).ToList();
                var menuListb = urPermissions.Where(o => o.aType == 2 && o.aParentId == item.Id && o.abName == "").ToList();
                foreach (var itemb in menuListb)
                {
                    UserMenub menub = new UserMenub()
                    {
                        aCode = itemb.aCode,
                        ahtmlIcon = itemb.ahtmlIcon,
                        amoduleIndex = itemb.amoduleIndex,
                        name = itemb.aName,  
                        url = itemb.ahtmlUrl,
                        aId = itemb.Id
                    };
                    var aIdb = module.aId;
                    module.userMenu.FirstOrDefault(o => o.aId == aId).childMenus.Add(menub);
                    module.userMenu.FirstOrDefault(o => o.aId ==aId).childMenus = module.userMenu.FirstOrDefault(o => o.aId == aId).childMenus.OrderBy(o => o.amoduleIndex).ToList();

                    var nowmenu = module.userMenu.FirstOrDefault(o => o.aId == aId).childMenus.FirstOrDefault(o => o.aId == itemb.Id);
                    AddMenuData(urPermissions, itemb.Id, ref nowmenu);
                }
            }
        }

        /// <summary>
        /// 设置权限信息
        /// </summary>
        /// <param name="urPermissions"></param>
        /// <param name="item"></param>
        /// <param name="modules"></param>
        /// <param name="module"></param>
        private static void InitAuthro(List<Menu> urPermissions, Menu item, List<UserModule> modules, UserModule module)
        {
            //获取用户角色模块按钮信息
            var actionListb = urPermissions.Where(o => o.aType == 3).ToList();
            foreach (var action in actionListb)
            {
                UserAction userAction = new UserAction();
                userAction.name = action.aName;
                userAction.url = action.aapiUrl;
                var ishave = false;
                //如果已经存在该模块菜单信息则不添加
                foreach (var md in modules)
                {
                    ishave = md.userAction.Any(o => o.name == action.aName);
                    if (ishave)
                    {
                        break;
                    }
                }
                if (!ishave)
                {
                    if (modules.Count > 0)
                    {
                        var old = modules.Any(o => o.name == module.name);
                        if (old)
                        {
                            modules.Where(o => o.name == module.name).FirstOrDefault().userAction.Add(userAction);
                        }
                        else
                        {
                            module.userAction.Add(userAction);
                        }
                    }
                    else
                    {
                        module.userAction.Add(userAction);
                    }
                }
            }
            if (module.userMenu.Count > 0)
                module.userMenu = module.userMenu.OrderBy(o => o.amoduleIndex).ToList();

            if (modules.Where(o => o.name == module.name).Count() == 0)
                modules.Add(module);
        }

        private delegate void DoTaskDlg(string rids, IMySqlSugarService MySqlDapperService);


        /// <summary>
        /// 角色资源导出数据设置
        /// </summary>
        /// <param name="excelName"></param>
        /// <param name="fileName"></param>
        /// <param name="list"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static MemoryStream ExportData(string fileName, string excelName, List<URPermissionExtend> list, out string msg)
        {
            msg = string.Empty;
            MemoryStream ms = ExcelUtil.GetExcelUtil.InitExportData(fileName, excelName, list, (row, cell, sheet1, TextSytle, srow, hssfworkbook) => {

                foreach (URPermissionExtend item in list)
                {
                    srow++;
                    row = sheet1.CreateRow(srow);
                   

                    //角色名称
                    cell = row.CreateCell(0);
                    cell.CellStyle = TextSytle;
                    cell.SetCellValue(item.rName);

                    //资源名称
                    cell = row.CreateCell(1);
                    cell.CellStyle = TextSytle;
                    cell.SetCellValue(item.aName);

                    //使用状态
                    cell = row.CreateCell(2);
                    cell.CellStyle = TextSytle;
                    cell.SetCellValue(item.status == 1 ? "启用" : "停用");
                }
            }, out msg, 2);
            return ms;
        }
    }
}
